package com.example.module_mine.register

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.app.NotificationCompat
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.base.BaseActivity
import com.example.module_mine.R
import com.example.module_mine.databinding.ActivityRegisterBinding
import com.example.module_mine.databinding.RegisterFramlayoutBinding
import com.example.module_mine.register.viewmodel.RegisterViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlin.random.Random

@AndroidEntryPoint
@Route(path = "/register/RegisterActivity")
class RegisterActivity : BaseActivity<RegisterViewModel, ActivityRegisterBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_register
    private val mViewModel: RegisterViewModel by viewModels()
    lateinit var register_binding: RegisterFramlayoutBinding
    var s = ""

    //60秒倒计时
    var remainingSeconds = 6
    val handler = Handler(Looper.getMainLooper())


    override fun initData() {
        super.initData()

        //不可点击\灰色背景
        notclick()
        //点击获取验证码
        getcodeclick()
        //点击注册
        registerclcik()
        //监听注册成功
        registersuccesslistener()


    }

    private fun notclick() {
        register_binding.btnRegister.isEnabled = false
        register_binding.btnRegister.setBackgroundColor(Color.GRAY)
    }

    private fun registersuccesslistener() {
        mViewModel.registerlivedata.observe(this) {
            if (it.equals("注册失败，账号或密码已被注册")) {
                //清空输入框
                Assignmentnull()
                register_binding.registerUsername.requestFocus()
                Toast.makeText(this, "" + it, Toast.LENGTH_SHORT).show()
                return@observe
            }
            if (it.equals("注册成功")) {
                Toast.makeText(this, "" + it, Toast.LENGTH_SHORT).show()
                ARouter.getInstance().build("/login/login")
                    .withString("un", register_binding.registerUsername.text.toString())
                    .withString("pw", register_binding.registerPassword.text.toString())
                    .navigation()
                return@observe
            }


        }

    }

    private fun Assignmentnull() {
        register_binding.registerUsername.text = null
        register_binding.registerPassword.text = null
        register_binding.registerTwopassword.text = null
    }

    private fun registerclcik() {
        register_binding.btnRegister.setOnClickListener {
            //判断输入框是否为空

            if (register_binding.registerUsername.text.toString()
                    .isEmpty() || register_binding.registerPassword.text.toString()
                    .isEmpty() || register_binding.registerTwopassword.text.toString().isEmpty()
            ) {
                Toast.makeText(this, R.string.user_or_pass_isnull, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (!register_binding.registerPassword.text.toString()
                    .equals(register_binding.registerTwopassword.text.toString())

            ) {
                Toast.makeText(this, R.string.password_not_equals, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (!register_binding.wirteVerftcode.text.toString().equals(s)) {
                Toast.makeText(this, R.string.peease_write_verftcode, Toast.LENGTH_SHORT)
                    .show()
                return@setOnClickListener
            }



            if (register_binding.registerUsername.text.toString()
                    .isNotEmpty()
                && register_binding.registerPassword.text.toString().isNotEmpty()
                && register_binding.registerTwopassword.text.toString().isNotEmpty()
                && register_binding.wirteVerftcode.text.toString().isNotEmpty()
            ) {
                mViewModel.register(
                    register_binding.registerUsername.text.toString(),
                    register_binding.registerPassword.text.toString()
                )
            } else {
                Toast.makeText(this, R.string.user_and_pass_not_null, Toast.LENGTH_SHORT).show()
            }

        }
    }

    private fun getcodeclick() {

        register_binding.getVerftcode.setOnClickListener {
            showSimpleNotification(this)

            val countdownRunnable = object : Runnable {
                override fun run() {
                    register_binding.getVerftcode.text = "${remainingSeconds}s"

                    if (remainingSeconds > 0) {
                        register_binding.getVerftcode.isEnabled = false
                        register_binding.getVerftcode.setBackgroundColor(Color.GRAY)
                        remainingSeconds--
                        handler.postDelayed(this, 1000)
                    } else {
                        register_binding.getVerftcode.isEnabled = true
                        register_binding.getVerftcode.setBackgroundColor(Color.parseColor("#4169E1"))
                        register_binding.getVerftcode.text = "重新获取倒计时！"
                        remainingSeconds = 6

                    }
                }
            }

            // 开始倒计时
            handler.post(countdownRunnable)


            // 取消倒计时
//           handler.removeCallbacks(countdownRunnable)



            //消炎不予，只是一味的敲代码
        }
    }

    override fun initView() {
        super.initView()


        //创建通道
        createNotificationChannel(this)
        searchBindint()

    }


    private fun searchBindint() {
        register_binding = DataBindingUtil.inflate(
            layoutInflater,
            R.layout.register_framlayout,
            mBinding.registerFramelayout,
            false
        )
        mBinding.registerFramelayout.addView(register_binding.root)
    }

    override fun initListener() {
        super.initListener()
    }


    fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "channel_id", // 渠道ID（唯一）
                "Channel Name", // 用户可见的渠道名称
                NotificationManager.IMPORTANCE_DEFAULT // 优先级
            ).apply {
                description = "Channel Description" // 渠道描述
            }

            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    //发送通知
    @SuppressLint("UnsafeIntentLaunch")
    fun showSimpleNotification(context: Context) {
        // 1. 创建点击通知后的跳转 Intent
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )


        s = ""
        for (i in 0..5) {
            s += Random.nextInt(9)
        }


        // 2. 构建通知
        val notification = NotificationCompat.Builder(context, "channel_id")
            .setSmallIcon(R.drawable.logo) // 必须设置的小图标
            .setContentTitle("您的验证码是")
            .setContentText("" + s)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent) // 点击后的行为
            .setAutoCancel(true) // 点击后自动消失
            .build()

        // 3. 发送通知
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(1, notification) // 通知ID（唯一，用于更新或取消）
        register_binding.btnRegister.isEnabled = true
        register_binding.btnRegister.setBackgroundColor(Color.parseColor("#4169E1"))
    }


}